// 备用语音识别服务 - 使用浏览器原生Web Speech API
export class FallbackVoiceRecognitionService {
    private recognition: any = null;
    private isRecording = false;
    private onResult?: (text: string) => void;
    private onError?: (error: string) => void;
    private onStatusChange?: (status: 'idle' | 'recording' | 'processing') => void;

    constructor() {
        this.initializeRecognition();
    }

    // 初始化语音识别
    private initializeRecognition() {
        if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
            const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
            this.recognition = new SpeechRecognition();

            // 配置识别参数
            this.recognition.continuous = true;
            this.recognition.interimResults = true;
            this.recognition.lang = 'zh-CN';
            this.recognition.maxAlternatives = 1;

            // 设置事件处理器
            this.recognition.onstart = () => {
                console.log('浏览器语音识别开始');
                this.isRecording = true;
                this.onStatusChange?.('recording');
            };

            this.recognition.onresult = (event: any) => {
                let finalTranscript = '';
                let interimTranscript = '';

                for (let i = event.resultIndex; i < event.results.length; i++) {
                    const transcript = event.results[i][0].transcript;
                    if (event.results[i].isFinal) {
                        finalTranscript += transcript;
                    } else {
                        interimTranscript += transcript;
                    }
                }

                if (finalTranscript) {
                    console.log('浏览器识别结果:', finalTranscript);
                    this.onResult?.(finalTranscript);
                    this.onStatusChange?.('processing');
                }
            };

            this.recognition.onerror = (event: any) => {
                console.error('浏览器语音识别错误:', event.error);
                let errorMessage = '语音识别失败';

                switch (event.error) {
                    case 'network':
                        errorMessage = '网络连接失败，请检查网络连接';
                        break;
                    case 'not-allowed':
                        errorMessage = '麦克风权限被拒绝，请允许麦克风访问';
                        break;
                    case 'no-speech':
                        errorMessage = '未检测到语音，请重试';
                        break;
                    case 'audio-capture':
                        errorMessage = '音频捕获失败，请检查麦克风';
                        break;
                    case 'service-not-allowed':
                        errorMessage = '语音识别服务不可用';
                        break;
                    default:
                        errorMessage = `语音识别错误: ${event.error}`;
                }

                this.onError?.(errorMessage);
                this.isRecording = false;
                this.onStatusChange?.('idle');
            };

            this.recognition.onend = () => {
                console.log('浏览器语音识别结束');
                this.isRecording = false;
                this.onStatusChange?.('idle');
            };

            console.log('浏览器Web Speech API 初始化成功');
        } else {
            console.warn('浏览器不支持Web Speech API');
        }
    }

    // 开始录音
    async startRecording(
        onResult: (text: string) => void,
        onError: (error: string) => void,
        onStatusChange: (status: 'idle' | 'recording' | 'processing') => void
    ) {
        this.onResult = onResult;
        this.onError = onError;
        this.onStatusChange = onStatusChange;

        if (!this.recognition) {
            onError('浏览器不支持语音识别功能');
            return;
        }

        try {
            this.recognition.start();
            console.log('开始浏览器语音识别');
        } catch (error) {
            console.error('启动浏览器语音识别失败:', error);
            onError('启动语音识别失败，请重试');
        }
    }

    // 停止录音
    stopRecording() {
        if (this.recognition && this.isRecording) {
            this.recognition.stop();
            this.isRecording = false;
            console.log('停止浏览器语音识别');
        }
    }

    // 检查是否支持
    isSupported(): boolean {
        return !!(this.recognition);
    }

    // 清理资源
    cleanup() {
        if (this.recognition) {
            this.recognition.stop();
            this.recognition = null;
        }
        this.isRecording = false;
        console.log('浏览器语音识别服务清理完成');
    }
}

// 创建单例实例
export const fallbackVoiceRecognitionService = new FallbackVoiceRecognitionService();

